#import "GameOverScene.h"
#import "GameScene.h"
#import "MainMenuScene.h"
#import "LeaderboardScene.h"
#import "Constants.h"
#import "CoreDataHelper.h"
#import "SoundHandler.h"
#import "SocialSharingHelper.h"

@interface GameOverScene ()

@property UITextField* textField;
@property NSUInteger score;
@property SKLabelNode* submitLabelButton;
@property BOOL isSubmitPressed;
@property SocialSharingHelper* social;
@property BOOL gameIsWon;
@end

@implementation GameOverScene

BOOL isGameOver = NO;
static float scaleCoeficient;
static float offset;

-(id)initWithSize:(CGSize)size score: (NSInteger)player_score gameIsWon:(BOOL) winner{ //updated the existing method
    if (self = [super initWithSize:size]) {
        self.social=[[SocialSharingHelper alloc] init];
        scaleCoeficient= size.height/640;
        offset= size.height/8;
    
        if (!isGameOver) {
            isGameOver = YES;
        }
        
        //playing game over sound
        
        self.backgroundColor = [SKColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
        NSString* message;
        if (winner) {
            self.gameIsWon=YES;
            message=winningText;
            [[SoundHandler sharedSoundPlayer] playBackgroundMusicWithURL:winningSound andExtension:@"mp3"];
        }
        else {
            self.gameIsWon=NO;
            message=gameOverText;
            [[SoundHandler sharedSoundPlayer] playBackgroundMusicWithURL:gameOverSound andExtension:@"mp3"];
            
        }
        
        SKLabelNode *label = [SKLabelNode labelNodeWithFontNamed:labelFontName];
        label.text = message;
        label.fontSize = 60;
        label.fontColor = [SKColor redColor];
        [label setScale:scaleCoeficient];
        label.position = CGPointMake(self.size.width/2, self.size.height-offset);
        [self addChild:label];
        
        NSString * playerscoremsg = [NSString stringWithFormat:@"Player Score: %ld",(long)player_score];
        self.score=player_score;
        SKLabelNode *playerscore = [SKLabelNode labelNodeWithFontNamed:labelFontName];
        playerscore.text = playerscoremsg;
        playerscore.fontColor = [SKColor blackColor];
        [playerscore setScale:scaleCoeficient];
        playerscore.position = CGPointMake(self.size.width/2, self.size.height -(1.8)*offset);
        playerscore.name = @"Player Score";
        [self addChild:playerscore];
        
        
        
        NSString * retrymessage= @"Try Again";
        SKLabelNode *retryButton = [SKLabelNode labelNodeWithFontNamed:labelFontName];
        retryButton.text = retrymessage;
        retryButton.fontColor = [SKColor blackColor];
        retryButton.position = CGPointMake(self.size.width/2, 3*offset);
        retryButton.name = @"retry";
        [retryButton setScale:scaleCoeficient];
        [self addChild:retryButton];
        
        NSString * mainMenu= @"Main Menu";
        SKLabelNode * mainMenuButton = [SKLabelNode labelNodeWithFontNamed:labelFontName];
        mainMenuButton.text = mainMenu;
        mainMenuButton.fontColor = [SKColor blackColor];
        mainMenuButton.position = CGPointMake(self.size.width/2, 2*offset);
        [mainMenuButton setScale:scaleCoeficient];
        mainMenuButton.name = @"mainMenu";
        [self addChild:mainMenuButton];
        
    }
    
    return self;
}
-(void)didMoveToView:(SKView *)view {
    offset=self.scene.size.height/3;
    self.isSubmitPressed = NO;
    if (![CoreDataHelper checkMinScore:self.score]) {
        return;
    }
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake((self.scene.frame.size.width -kTextFieldWidth )/2, self.scene.size.height - 2*(offset), kTextFieldWidth, kTextFieldHeight)];
    self.textField.borderStyle = UITextBorderStyleRoundedRect;
    self.textField.textColor = [UIColor blackColor];
    
    self.textField.font = [UIFont systemFontOfSize:17.0];
    self.textField.placeholder =gameOverSceneTextFieldPlaceholder;
    self.textField.backgroundColor = [UIColor whiteColor];
    self.textField.alpha=0.0;
    self.textField.delegate = self;
    [self.view addSubview:self.textField];
    [UIView animateWithDuration:1.5 animations:^{
        self.textField.alpha=1.0;
    }];
    NSString * submit= @"Submit";
    self.submitLabelButton = [SKLabelNode labelNodeWithFontNamed:labelFontName];
    self.submitLabelButton.text = submit;
    self.submitLabelButton.fontColor = [SKColor blackColor];
    
    self.submitLabelButton.position = CGPointMake((self.scene.frame.size.width)/2 + (kTextFieldWidth)/2 + offset/2, self.scene.size.height -(offset) - kTextFieldHeight);
    self.submitLabelButton.name = @"save";
    [self.submitLabelButton setScale:scaleCoeficient];
    [self addChild:self.submitLabelButton];
}

// hides the keyboard when the return button is pressed
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];
    SKView * skView = (SKView *)self.view;
    [[self view] endEditing:YES];
    
    
    //Starting new GameScene
    if ([node.name isEqualToString:@"retry"]) {
        [self.textField removeFromSuperview];
        isGameOver = NO;
        SKTransition *reveal =[SKTransition flipHorizontalWithDuration:0.5];
        
        GameScene * scene = [GameScene sceneWithSize:self.view.bounds.size];
        scene.scaleMode = SKSceneScaleModeAspectFill;
        [self.view presentScene:scene transition: reveal];
    }
    
    //returning to the Main Menu Scene
    if ([node.name isEqualToString:@"mainMenu"]) {
        [self.textField removeFromSuperview];
        
        SKScene * scene = [MainMenuScene sceneWithSize:skView.bounds.size];
        scene.scaleMode = SKSceneScaleModeAspectFill;
        SKTransition *reveal = [SKTransition doorsOpenVerticalWithDuration:0.5];
        
        // Present the scene.
        [skView presentScene:scene transition:reveal];
    }
    if ([node.name isEqualToString:@"leaderboard"]) {
        
        [self.textField removeFromSuperview];
        LeaderboardScene* leaderboard=[[LeaderboardScene alloc] initWithSize:skView.bounds.size andPreviousScene:@"GameOver" andScore:self.score];
        leaderboard.scaleMode=SKSceneScaleModeAspectFill;
        SKTransition* reveal=[SKTransition doorsOpenVerticalWithDuration:0.5];
        [skView presentScene:leaderboard transition:reveal];
    }
    if ([node.name isEqualToString:@"save"] && ![self.textField.text isEqualToString:@""]) {
        offset= self.scene.size.height/8;
        if (self.isSubmitPressed ==NO) {
            
            NSString * leaderboard= @"Leaderboards";
            SKLabelNode * leaderboardButton = [SKLabelNode labelNodeWithFontNamed:labelFontName];
            leaderboardButton.text = leaderboard;
            leaderboardButton.fontColor = [SKColor blackColor];
            leaderboardButton.position = CGPointMake(self.size.width/2, offset);
            leaderboardButton.name = @"leaderboard";
            [leaderboardButton setScale:scaleCoeficient];
            [self addChild:leaderboardButton];
            leaderboardButton.alpha=0.0;
            [leaderboardButton runAction:[SKAction fadeInWithDuration:1.0]]
            ;
            NSNumber* scoreToSave=[NSNumber numberWithInteger:self.score];
            [[CoreDataHelper sharedCoreDataHelper] addPlayerWithName:self.textField.text andScore:scoreToSave];
            [self.submitLabelButton runAction:[SKAction fadeOutWithDuration:1.0]];
            [UIView animateWithDuration:0.5 animations:^{
                self.textField.alpha=0.0;
            }];
            self.isSubmitPressed=YES;
            CGPoint facebookPosition=CGPointMake((self.scene.frame.size.width)/2 - offset, self.scene.size.height -3*offset);
            SKSpriteNode * facebookButton= [Constants createSpriteNodeWithImage:@"Facebook" andName:@"facebook" andPosition:facebookPosition andAlpha:0.0 andScale:scaleCoeficient* 0.4];
            facebookButton.name=@"facebook";
            [self addChild:facebookButton];
            CGPoint twitterPosition=CGPointMake((self.scene.frame.size.width)/2 + offset, self.scene.size.height -3*offset);
            SKSpriteNode * twitterButton= [Constants createSpriteNodeWithImage:@"Twitter" andName:@"twitter" andPosition:twitterPosition andAlpha:0.0 andScale:scaleCoeficient* 0.4];
            [self addChild:twitterButton];
            SKAction* action=[SKAction fadeAlphaTo:1.0 duration:2.0];
            [twitterButton runAction:action];
            [facebookButton runAction:action];
        }
        
    }
    if ([node.name isEqualToString:@"facebook"]) {
        [self.social postToFacebookOrTwitterFromCurrentController:self.view.window.rootViewController withPoints:self.score andIsGameWon:self.gameIsWon andSocialType:Facebook];
    }
    if ([node.name isEqualToString:@"twitter"]) {
        [self.social postToFacebookOrTwitterFromCurrentController:self.view.window.rootViewController withPoints:self.score andIsGameWon:self.gameIsWon andSocialType:Twitter];
    }
}
@end
